package com.clpms.service.impl;

import com.clpms.bean.enumBean.ErrorCodeEnum;
import com.clpms.bean.req.SchoolAddReq;
import com.clpms.bean.resp.QuerySchoolResp;
import com.clpms.bean.resp.SchoolAddResp;
import com.clpms.dao.mapper.SchoolDao;
import com.clpms.dao.pojo.School;
import com.clpms.service.SchoolService;
import com.clpms.utils.CommonException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author caixinyong
 * @date 2023/5/5 4:20 PM
 */

@Service
@Slf4j
public class SchoolServiceImpl implements SchoolService {

	@Resource
	private SchoolDao schoolDao;


	/**
	 * 添加学校
	 *
	 * @param req
	 * @return
	 */
	@Override
	public SchoolAddResp add(SchoolAddReq req) {
		String schoolName = req.getName();
		//1.校验学校名称是否重复
		List<School> schoolList = schoolDao.selectByNameList(Collections.singletonList(schoolName));
		if (CollectionUtils.isNotEmpty(schoolList)) {
			throw new CommonException(ErrorCodeEnum.PARAM_ERROR.getCode(), "学校名称重复");
		}
		//2.添加学校
		schoolDao.insertBatch(
				Collections.singletonList(School.builder().name(schoolName).build())
		);

		return SchoolAddResp.builder().successFlag(Boolean.TRUE).message("添加学校成功").build();
	}


	@Override
	public List<QuerySchoolResp> queryAllSchool() {
		List<School> schoolList = schoolDao.queryAllSchool();
		if (CollectionUtils.isEmpty(schoolList)) {
			throw new CommonException(ErrorCodeEnum.FAIL, "没有学校");
		}
		List<QuerySchoolResp> schoolResps =
				schoolList.stream().map(school ->
						QuerySchoolResp.builder().id(school.getId()).name(school.getName()).build()
				).collect(Collectors.toList());
		return schoolResps;
	}
}
